<template>
  <div class="my-exam-records-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>我的考试记录</span>
        </div>
      </template>

      <div v-if="isLoading" v-loading="isLoading" style="min-height: 200px;"></div>
      
      <div v-else-if="errorMsg">
          <el-alert type="error" :title="errorMsg" show-icon :closable="false"></el-alert>
      </div>

      <div v-else-if="recordsData">
          <!-- 统计信息 -->
          <el-descriptions title="考试统计概览" :column="3" border class="stats-section">
              <el-descriptions-item label="参与考试总数">{{ recordsData.totalExams || 0 }}</el-descriptions-item>
              <el-descriptions-item label="已完成考试">{{ recordsData.completedExams || 0 }}</el-descriptions-item>
              <el-descriptions-item label="通过考试数">{{ recordsData.passedExams || 0 }}</el-descriptions-item>
              <el-descriptions-item label="平均得分">
                <el-tag type="success" v-if="recordsData.averageScore !== null">{{ recordsData.averageScore.toFixed(1) }}</el-tag>
                <span v-else>-</span>
              </el-descriptions-item>
               <el-descriptions-item label="通过率">
                 <el-tag type="primary" v-if="recordsData.passRate !== null">{{ (recordsData.passRate * 100).toFixed(0) }}%</el-tag>
                 <span v-else>-</span>
               </el-descriptions-item>
          </el-descriptions>
          
          <el-divider></el-divider>
          
          <h3>考试记录列表</h3>
           <el-table :data="recordsData.examRecords" style="width: 100%">
                <el-table-column prop="examId" label="考试ID" width="80"></el-table-column>
                <el-table-column prop="examTitle" label="考试名称" min-width="150"></el-table-column>
                <el-table-column prop="submitTime" label="提交时间" width="180">
                    <template #default="{ row }">{{ formatDateTime(row.submitTime) }}</template>
                </el-table-column>
                <el-table-column prop="score" label="得分" width="100">
                    <template #default="{ row }">
                        <span v-if="row.status === 'MARKED'">{{ row.score !== null ? row.score.toFixed(1) : '-' }} / {{ row.totalScore || '-' }}</span>
                        <el-tag type="info" v-else-if="row.status === 'SUBMITTED'">待批改</el-tag>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="passed" label="是否通过" width="100">
                    <template #default="{ row }">
                        <el-tag v-if="row.status === 'MARKED' && row.passed !== null" :type="row.passed ? 'success' : 'danger'">
                            {{ row.passed ? '通过' : '未通过' }}
                        </el-tag>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                 <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getRecordStatusTagType(row.status)">{{ getRecordStatusText(row.status) }}</el-tag>
                    </template>
                 </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button 
                          v-if="row.status === 'MARKED' || row.status === 'SUBMITTED'" 
                          type="primary" 
                          link 
                          size="small" 
                          @click="viewRecordDetail(row.examId)"
                        >
                          查看详情
                        </el-button>
                         <span v-else>-</span>
                    </template>
                </el-table-column>
            </el-table>
      </div>
       <el-empty v-else description="暂无考试记录"></el-empty>

    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getStudentExamRecordsList } from '@/services/examService';
import { ElCard, ElTable, ElTableColumn, ElTag, ElDescriptions, ElDescriptionsItem, ElDivider, ElEmpty, ElAlert } from 'element-plus';

const router = useRouter();

const recordsData = ref(null);
const isLoading = ref(false);
const errorMsg = ref('');

const loadRecords = async () => {
    isLoading.value = true;
    errorMsg.value = '';
    try {
        const response = await getStudentExamRecordsList();
        if (response && response.success) {
            recordsData.value = response.data;
        } else {
            errorMsg.value = response?.message || '加载考试记录列表失败';
            recordsData.value = null;
            // ElMessage.error(errorMsg.value); // Service 层已提示，这里用 Alert 显示
        }
    } catch (error) {
        console.error("Error fetching student exam records:", error);
        errorMsg.value = '加载数据时发生网络或未知错误';
        recordsData.value = null;
    } finally {
        isLoading.value = false;
    }
};

// --- Helper Functions (可以提取到 utils) ---
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-';
  try { return new Date(dateTimeString).toLocaleString(); } catch (e) { return dateTimeString; }
};
const getRecordStatusText = (status) => {
  const map = { SUBMITTED: '已提交', MARKED: '已批改' };
  return map[status] || status;
};
const getRecordStatusTagType = (status) => {
  const map = { SUBMITTED: 'primary', MARKED: 'success' };
  return map[status] || 'info';
};
// -------------------------------------------

const viewRecordDetail = (examId) => {
    if (!examId) return;
    router.push({ name: 'MyExamRecordDetail', params: { examId: examId } });
};

onMounted(() => {
    loadRecords();
});
</script>

<style scoped>
.my-exam-records-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.stats-section {
    margin-bottom: 20px;
}
</style> 